import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while(true){
            Socket socket = serverSocket.accept();
            processConnection(socket);
        }
    }

    private void processConnection(Socket socket){
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                Scanner sc = new Scanner(inputStream);
                if(!sc.hasNext()){
                    break;
                }
                String request = sc.next();
                String response = process(request);
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d] req: %s, resp: %s", socket.getInetAddress().toString(), socket.getPort(), request, response);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(8080);
        server.start();
    }
}
